//
//  RadioCollectionViewController.m
//  SuiRan
//
//  Created by lanou3g on 15-4-27.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "RadioCollectionViewController.h"
#import "Radio.h"
#import "Userinfo.h"
#import "AFHTTPRequestOperationManager.h"
#import "RadioCollectionViewCell.h"
#import "UIImageView+WebCache.h"
#import "RadioCollectionView.h"
#import "RadioDetailTableViewController.h"
#import "MJRefresh.h"
#import "RESideMenu.h"
#import "RadioDetailContactViewController.h"


@interface RadioCollectionViewController ()
@property (nonatomic, retain) RadioCollectionView *radioCV;

@property (nonatomic, retain) NSMutableArray *alllistArray;
@property (nonatomic, retain) NSMutableArray *hotlistArray;
@property (nonatomic, retain) NSMutableArray *hotUserinfoArray;
@property (nonatomic, retain) NSMutableArray *allUserinfoArray;
@property (nonatomic, retain) NSMutableArray *countArray;

@property (nonatomic, assign) NSInteger startNumber;

@property (nonatomic, retain) RadioDetailContactViewController * rdCVC;

@end

@implementation RadioCollectionViewController

static NSString * const reuseIdentifier = @"Cell";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 注册header
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    
    
    self.navigationItem.title = @"电台";
    self.collectionView.backgroundColor = [UIColor whiteColor];

    // 设置左navigationbarButton
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"menu"] style:UIBarButtonItemStylePlain target:self action:@selector(presentLeftMenuViewController:)] autorelease];
    
    // 设置右navigationbarButton
   
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"RightMenu"] style:UIBarButtonItemStylePlain target:self action:@selector(presentRightMenuViewController:)] autorelease];
  
    
    
    [self.collectionView registerNib:[UINib nibWithNibName:@"RadioCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:reuseIdentifier];
    [self JSONData];
    [self refreshData];
    
    
}



#pragma mark - 刷新数据
- (void)refreshData
{
    __block typeof(self) weakSelf = self;
    
    // 下拉刷新
    [self.collectionView addLegendHeaderWithRefreshingBlock:^{
        NSLog(@"下拉刷新");
        
        // 设置字体
        self.collectionView.header.font = [UIFont fontWithName:@"Optima" size:12];
        
        
        
        [self JSONData];
        
        // 计数  控制刷新后start为初始量
        _startNumber = 9;
        // 结束刷新
        [weakSelf.collectionView.header endRefreshing];
        [weakSelf.collectionView reloadData];
        
        
    }];
    
    // 上拉刷新
    [self.collectionView addLegendFooterWithRefreshingBlock:^{
        [self refreshJSONData];
        self.collectionView.header.font = [UIFont fontWithName:@"Optima" size:12];

        // 结束刷新
        [weakSelf.collectionView.footer endRefreshing];
        [weakSelf.collectionView reloadData];
        
        
    }];
    
    [self.collectionView.footer setTitle:@"" forState:MJRefreshFooterStateIdle];
    
    
}




#pragma mark - 解析数据
- (void)JSONData
{
    
    self.alllistArray = [NSMutableArray array];
    self.hotlistArray = [NSMutableArray array];
    self.allUserinfoArray = [NSMutableArray array];
    self.hotUserinfoArray = [NSMutableArray array];
    
    __block typeof(self) weakSelf = self;
    NSURL *url = [NSURL URLWithString:kRadioMainList];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    // 准备AFHTTPRequestOperation
    AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] initWithRequest:request] autorelease];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData *data = operation.responseData;
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        //        NSLog(@"！！！%@", dic[@"data"]);
        //                        NSLog(@"%@", dic[@"data"][@"alllist"]);
        //        NSLog(@"%@", responseObject);
        //        NSLog(@"%@", _alllistArray);
#pragma mark - 遍历hotlist
        for (NSDictionary *item in dic[@"data"][@"hotlist"]) {
            Radio *r = [[Radio new] autorelease];
            [r setValuesForKeysWithDictionary:item];
            [weakSelf.hotlistArray addObject:r];
        }
        //        NSLog(@"hotlistArray=======%@", _hotlistArray);
        
#pragma mark - 遍历hotlist中的userinfo
        for (NSInteger i = 0; i < _hotlistArray.count; i++) {
            NSMutableDictionary *item = dic[@"data"][@"hotlist"][i][@"userinfo"];
            Userinfo *u = [[Userinfo new] autorelease];
            [u setValuesForKeysWithDictionary:item];
            [_hotUserinfoArray addObject:u];
        }
        //        NSLog(@"hotlistArray=======%@", _hotUserinfoArray);
        
#pragma mark - 遍历alllist
        for (NSDictionary *item in dic[@"data"][@"alllist"]) {
            Radio *r = [[Radio new] autorelease];
            [r setValuesForKeysWithDictionary:item];
            [weakSelf.alllistArray addObject:r];
        }
        //        NSLog(@"alllistArray=======%@", _alllistArray);
        
#pragma mark - 遍历hotlist中的userinfo
        for (NSInteger i = 0; i < _alllistArray.count; i++) {
            NSMutableDictionary *item = dic[@"data"][@"alllist"][i][@"userinfo"];
            Userinfo *u = [[Userinfo new] autorelease];
            [u setValuesForKeysWithDictionary:item];
            [_allUserinfoArray addObject:u];
        }
        //        NSLog(@"hotlistArray=======%@", _allUserinfoArray);
        
        [weakSelf.collectionView reloadData];
        
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Failure: %@", [error localizedDescription]);
    }];
    // 开始获取数据
    [operation start];
}

#pragma mark - 上拉解析新数据将数据加入数组
- (void)refreshJSONData
{
    
    _startNumber += 9;
    NSString *startN = [NSString stringWithFormat:@"%ld", (long)_startNumber];
    NSLog(@"count = %@", startN);
    
    
    __block typeof(self) weakSelf = self;
    
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSDictionary *params = @{@"start" : startN};
    [manager POST:kRadioMainListRefresh parameters:params success:
     
     ^(AFHTTPRequestOperation *operation, id responseObject) {
         NSData *data = operation.responseData;
         NSDictionary *dict = [NSJSONSerialization  JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
         
#pragma mark - 遍历list
         weakSelf.countArray = [NSMutableArray array];
         for (NSDictionary *item in dict[@"data"][@"list"]) {
             Radio *r = [[Radio new] autorelease];
             [r setValuesForKeysWithDictionary:item];
             [weakSelf.alllistArray addObject:r];
             
             [weakSelf.countArray addObject:r];
             
             
         }
         
         
#pragma mark - 遍历list中的userinfo
         for (NSInteger i = 0; i < _countArray.count; i++) {
             
             
             //                 NSLog(@"!!!!!!!!!!!!!!!!!!!!!!!%ld", _countArray.count);
             NSMutableDictionary *item = dict[@"data"][@"list"][i][@"userinfo"];
             Userinfo *u = [[Userinfo new] autorelease];
             [u setValuesForKeysWithDictionary:item];
             [weakSelf.allUserinfoArray addObject:u];
         }
         
         [self.collectionView reloadData];
         
         
         
     }
          failure:^(AFHTTPRequestOperation *operation, NSError *error) {
              
              NSLog(@"下载错误 is %@",error);
              
          }];
    
}




#pragma mark <UICollectionViewDataSource>


#pragma mark - 设置每个CollectionView的Section的个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    return 2;
}

#pragma mark - 设置每个section的item的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    if (section == 0) {
        
        return _hotlistArray.count;
    } else {
        return _alllistArray.count;
    }
}

#pragma mark - 每个item返回的内容
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    RadioCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    if (indexPath.section == 0) {
        Radio *r = _hotlistArray[indexPath.row];
        cell.ImageLabel.text = r.title;
        
        Userinfo *u = _hotUserinfoArray[indexPath.row];
        cell.UserLabel.text = [NSString stringWithFormat:@"by:%@",u.uname];
        
        [cell.RadioImage sd_setImageWithURL:[NSURL URLWithString:r.coverimg]];
        
    } else {
        Radio *r = _alllistArray[indexPath.row];
        cell.ImageLabel.text = r.title;
        
        Userinfo *u = _allUserinfoArray[indexPath.row];
        cell.UserLabel.text = [NSString stringWithFormat:@"by:%@",u.uname];;
        
        [cell.RadioImage sd_setImageWithURL:[NSURL URLWithString:r.coverimg]];
    }
    
    
    return cell;
}

#pragma mark - 设置每个item点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    RadioDetailTableViewController *rdTVC = [RadioDetailTableViewController new];
    
    if (indexPath.section == 0) {
        Radio *r = _hotlistArray[indexPath.row];
        rdTVC.radio = r;
    } else {
        Radio *r = _alllistArray[indexPath.row];
        rdTVC.radio = r;
    }
    
    [self.navigationController pushViewController:rdTVC animated:YES];
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    
    
    
    UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10.0 / 375 *kScreenWidth , 8.0 / 667 * kScreenHeight, 200.0 / 375 * kScreenWidth, 20.0 / 667 * kScreenHeight)];
    NSArray *arr = @[@"精选电台 · Featured Radio", @"全部电台 · All Radio"];
    label.backgroundColor = [UIColor whiteColor];
    label.font = [UIFont fontWithName:@"Optima" size:12];
    label.text = arr[indexPath.section];
    label.textColor = [UIColor colorWithWhite:0.432 alpha:1.000];
    [headerView addSubview:label];
    
    
    
    return headerView;
    
    
}


- (void)dealloc
{
    [_alllistArray release];
    [_hotlistArray release];
    [_hotUserinfoArray release];
    [_allUserinfoArray release];
    [_countArray release];
    [super dealloc];
}

@end
